import { observable, computed, action, runInAction, asMap, toJS } from 'mobx';
import { message } from 'antd';
import { WeaTableNew } from 'comsMobx';
import { isEmpty, isArray, cloneDeep } from 'lodash';
import * as API from '../apis/odocRequest/odocRequest';

const { TableStore } = WeaTableNew;

export default class OdocRequestStore {
  /**
   * 节点列表
   */
  @observable
  nextNodeList = [];

  /**
   *  已设定的流转
   */
  @observable
  nodeOperatorMap = {};

  /**
   *  选中的流程
   */
  workflowid = '';

  /**
   * 流程名称
   */
  workflowName = '';

  /**
   * 结束本人处理
   */
  @observable
  isend = '1';

  /**
   * 签字意见
   */
  @observable
  remark = '';

  directname = '';

  @observable
  dialogVisible = observable.map ? observable.map({}) : asMap({}); // 弹窗显示属性

  /**
   * 选择常用方向的窗口中的表格
   */
  @observable
  tableStore = new TableStore();

  /**
   * 提交按钮禁用，避免冲突点击
   */
  btnforbiden = false;

  @computed get nodeOperatorList() {
    const nextNodeList = toJS(this.nextNodeList);
    const nodeOperatorMap = toJS(this.nodeOperatorMap);

    const operatorList = [];
    if (nextNodeList && nextNodeList.length > 0) {
      nextNodeList.forEach((item) => {
        const { nodeid } = item;
        const map = nodeOperatorMap[nodeid] || {};

        let userInfo = {};
        if (!isEmpty(map)) {
          const { userList = [], userIds, userNames } = map;
          userInfo = { userList, userIds, userNames };
        }

        operatorList.push({ ...item, ...userInfo });
      });
    }

    return operatorList;
  }

  @computed get selectedRowKeys() {
    const nextNodeList = toJS(this.nextNodeList);
    const selectedKeys = [];

    if (nextNodeList && nextNodeList.length > 0) {
      nextNodeList.forEach((item) => {
        const { nodeid, selected = false } = item;
        if (selected) {
          selectedKeys.push(nodeid);
        }
      });
    }

    return selectedKeys;
  }

  constructor() {
    this.controlDialogVisible = this.controlDialogVisible.bind(this);
    this.setMember = this.setMember.bind(this);
    this.loadData = this.loadData.bind(this);
    this.saveDirection = this.saveDirection.bind(this);
    this.resetStore = this.resetStore.bind(this);
    this.resetTableStore = this.resetTableStore.bind(this);
    this.getTableList = this.getTableList.bind(this);
  }

  @action
  controlDialogVisible(key, value = false) {
    this.dialogVisible.set(key, value);
  }

  @action
  setMember(obj = {}) {
    Object.assign(this, { ...obj });
  }

  @action('加载数据')
  loadData(params, callback) {
    API.loadData(params).then((data) => {
      const { success = 0 } = data;
      if (success == 1) {
        callback && typeof callback == 'function' && callback(data);

        const { nextNodeList, workflowid, workflowName } = data;
        runInAction(() => {
          this.nextNodeList = nextNodeList;
          this.workflowid = `${workflowid}`;
          this.workflowName = workflowName;
        });
      } else {
        const { msg } = data;
        if (msg) {
          message.error(msg);
        }
      }
    });
  }


  @action('从常用去向导入')
  importData(params, callback) {
    API.importData(params).then((data) => {
      const { success = 0 } = data;
      if (success == 1) {
        callback && typeof callback == 'function' && callback(data);

        const { nodeOperatorMap } = data;
        this.nodeOperatorMap = nodeOperatorMap;

        // 处理节点选中的情况
        const selectedKeys = [];
        for (let key in nodeOperatorMap) {
          // 需要将key转为数字
          selectedKeys.push(key * 1);
        }
        this.updateSelectKeys(selectedKeys);
      } else {
        const { msg } = data;
        if (msg) {
          message.error(msg);
        }
      }
    });
  }

  /**
   * 保存常用方向
   * @param param
   * @param calllback
   */
  saveDirection(para, calllback) {
    const nextDirections = this.getNextDirections();

    // 删除这些不需要往服务端发送的数据
    nextDirections.map((item) => {
      delete item.userList;
      delete item.sqlwhere;
      delete item.sqlwhere1;
    });

    const params = {
      directname: this.directname,
      workflowid: this.workflowid,
      nextDirections: JSON.stringify(nextDirections),
      ...para,
    };

    API.saveData(params).then((data) => {
      this.directname = '';
      calllback && calllback(data);
    });
  }

  getNextDirections() {
    const nextNodeList = toJS(this.nextNodeList);
    const nodeOperatorMap = toJS(this.nodeOperatorMap);

    const operatorList = [];
    if (nextNodeList && nextNodeList.length > 0) {
      nextNodeList.forEach((item) => {
        const { nodeid, selected = false } = item;
        const map = nodeOperatorMap[nodeid] || {};

        let userInfo = {};
        if (!isEmpty(map)) {
          const { userList = [], userIds, userNames } = map;
          userInfo = { userList, userIds, userNames };
        }

        if (selected) {
          operatorList.push({ ...item, ...userInfo });
        }
      });
    }

    return operatorList;
  }


  /**
   * 流程流转
   * @param param
   * @param callback
   */
  flowNext(param, callback) {
    const nextDirections = this.getNextDirections();

    // 删除这些不需要往服务端发送的数据
    nextDirections.map((item) => {
      delete item.userList;
      delete item.sqlwhere;
      delete item.sqlwhere1;
    });

    const params0 = {
      ...param,
      isend: this.isend,
      nextDirections: JSON.stringify(nextDirections),
    };

    API.flowNext(params0).then((data) => {
      callback && callback(data);
    });
  }

  @action('更新表格行数据')
  updateRow(recordId, rowData = {}) {
    const nodeOperatorMap = toJS(this.nodeOperatorMap);
    const operatorMap = nodeOperatorMap[recordId];
    const { userList = [] } = rowData;

    // 先做删除操作
    if (operatorMap && typeof operatorMap == 'object') {
      delete nodeOperatorMap[recordId];
    }

    if (userList.length > 0) {
      const newMap = cloneDeep(rowData);
      nodeOperatorMap[recordId] = newMap;
    }

    this.nodeOperatorMap = nodeOperatorMap;

    // 设置表格的选中
    const selected = userList.length > 0;
    selected && this.updateSelectKeys(recordId, selected);
  }

  @action('清空已选择的人员')
  clearRow(recordId) {
    const nodeOperatorMap = toJS(this.nodeOperatorMap);
    const operatorMap = nodeOperatorMap[recordId];

    if (operatorMap && typeof operatorMap == 'object') {
      delete nodeOperatorMap[recordId];
    }
    // updateSelectKeys(recordId, false);
    this.nodeOperatorMap = nodeOperatorMap;
  }

  /**
   *
   * @param recordId，可以是string或者array
   * @param selected
   */
  @action('设置流转环节表格的选中')
  updateSelectKeys(recordId, selected) {
    const nextNodeList = toJS(this.nextNodeList);

    const newList = [];

    if (isArray(recordId)) {
      // 批量时，设置选中节点，所有选中的都以传入的为准，不在此范围的，取消选中
      const idSet = new Set(recordId);
      nextNodeList.forEach((item) => {
        const { nodeid } = item;
        if (idSet.has(nodeid)) {
          item = { ...item, selected: true };
        } else {
          item = { ...item, selected: false };
        }
        newList.push(item);
      });
    } else if (nextNodeList && nextNodeList.length > 0) {
      nextNodeList.forEach((item) => {
        const { nodeid } = item;
        if (recordId == nodeid) {
          item = { ...item, selected };
        }
        newList.push(item);
      });
    }


    this.nextNodeList = newList;
  }

  @action
  getTableList(params) {
    API.getTableList(params).then((data) => {
      this.tableStore.getDatas(data.datas, 1);
    },
    );
  }

  @action
  resetStore() {
    this.nextNodeList = [];
    this.nodeOperatorMap = {};
    this.dialogVisible.clear();
    this.isend = '1';
    this.remark = '';
    this.workflowid = '';
    this.workflowName = '';
    this.directname = '';
    this.btnforbiden = false;
  }

  @action
  resetTableStore() {
    this.tableStore = new TableStore();
  }
}
